﻿// Forms/MultiRoundResultForm.cs
using MultiDAQ_Analysis.Models;
using Newtonsoft.Json;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Printing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace MultiDAQ_Analysis.View
{
    /// <summary>
    /// 多轮测量结果简化显示窗口
    /// </summary>
    public partial class MultiRoundResultForm : UIForm
    {
        private MultiRoundMeasurementData measurementData;

        // UI 控件
        private UIRichTextBox txtResultDisplay;
        private UIButton btnExport;
        private UIButton btnPrint;
        private UIButton btnPrintPreview;
        private UILabel lblTitleInfo;

        // 打印相关字段
        private PrintDocument printDocument;
        private PrintPreviewDialog printPreviewDialog;
        private string[] printLines;
        private int printLineIndex;

        // 用于组织轮次数据的辅助类
        private class RoundData
        {
            public int RoundNumber { get; set; }
            public List<ChannelRoundResult> Results { get; set; } = new List<ChannelRoundResult>();
        }

        private class ChannelRoundResult
        {
            public int ChannelIndex { get; set; }
            public double AlphaResult { get; set; }
            public double BetaResult { get; set; }
            public double AlphaCountRate { get; set; }
            public double BetaCountRate { get; set; }
            public DateTime Timestamp { get; set; }
            public long AlphaTotalCounts { get; set; }
            public long BetaTotalCounts { get; set; }
            public int MeasurementDurationSeconds { get; set; }
        }

        public MultiRoundResultForm(MultiRoundMeasurementData data)
        {
            measurementData = data;
            InitializeComponent();
            InitializePrintComponents();
            SetupForm();
            LoadData();
        }

        /// <summary>
        /// 初始化打印组件
        /// </summary>
        private void InitializePrintComponents()
        {
            printDocument = new PrintDocument();
            printDocument.PrintPage += PrintDocument_PrintPage;
            printDocument.DocumentName = "测量结果报告";

            printPreviewDialog = new PrintPreviewDialog();
            printPreviewDialog.Document = printDocument;
            printPreviewDialog.UseAntiAlias = true;
            printPreviewDialog.Size = new Size(1000, 700);
        }

        private void InitializeComponent()
        {
            this.SuspendLayout();

            this.Text = "测量结果";
            this.Size = new Size(1000, 700);
            this.StartPosition = FormStartPosition.CenterParent;
            this.ShowInTaskbar = false;
            this.MaximizeBox = true;
            this.MinimizeBox = false;
            this.BackColor = Color.White;
            this.Name = "MultiRoundResultForm";

            this.ResumeLayout(false);
        }

        private void SetupForm()
        {
            // 创建主布局
            var mainLayout = new TableLayoutPanel
            {
                Dock = DockStyle.Fill,
                ColumnCount = 1,
                RowCount = 3,
                Padding = new Padding(15)
            };

            // 设置行样式
            mainLayout.RowStyles.Add(new RowStyle(SizeType.Absolute, 60)); // 标题区
            mainLayout.RowStyles.Add(new RowStyle(SizeType.Percent, 100)); // 内容区
            mainLayout.RowStyles.Add(new RowStyle(SizeType.Absolute, 60)); // 按钮区

            // 创建标题区面板
            var titlePanel = CreateTitlePanel();
            mainLayout.Controls.Add(titlePanel, 0, 0);

            // 创建内容显示区
            txtResultDisplay = new UIRichTextBox
            {
                Dock = DockStyle.Fill,
                Font = new Font("Consolas", 9.5F),
                ReadOnly = true,
                BackColor = Color.White
            };
            mainLayout.Controls.Add(txtResultDisplay, 0, 1);

            // 创建底部按钮区
            var buttonPanel = CreateButtonPanel();
            mainLayout.Controls.Add(buttonPanel, 0, 2);

            this.Controls.Add(mainLayout);
        }

        private Panel CreateTitlePanel()
        {
            var titlePanel = new Panel
            {
                Dock = DockStyle.Fill,
                Height = 60,
                BackColor = Color.FromArgb(243, 249, 255)
            };

            string measurementTypeDisplay = GetMeasurementTypeDisplayName(measurementData.MeasurementType);
            string titleText = $"测量结果 - {measurementTypeDisplay} (共{measurementData.TotalRounds}轮)";

            lblTitleInfo = new UILabel
            {
                Text = titleText,
                AutoSize = true,
                Font = new Font("微软雅黑", 14F, FontStyle.Bold),
                ForeColor = Color.FromArgb(64, 158, 255),
                Location = new Point(20, 18)
            };

            titlePanel.Controls.Add(lblTitleInfo);

            return titlePanel;
        }

        private Panel CreateButtonPanel()
        {
            var buttonPanel = new Panel
            {
                Dock = DockStyle.Fill,
                Height = 60
            };

            btnExport = new UIButton
            {
                Text = "导出报告",
                Size = new Size(100, 40),
                FillColor = Color.FromArgb(103, 194, 58),
                ForeColor = Color.White,
                Cursor = Cursors.Hand,
                Anchor = AnchorStyles.Bottom | AnchorStyles.Right
            };
            btnExport.Click += BtnExport_Click;

            btnPrintPreview = new UIButton
            {
                Text = "打印预览",
                Size = new Size(100, 40),
                FillColor = Color.FromArgb(54, 159, 255),
                ForeColor = Color.White,
                Cursor = Cursors.Hand,
                Anchor = AnchorStyles.Bottom | AnchorStyles.Right
            };
            btnPrintPreview.Click += BtnPrintPreview_Click;

            btnPrint = new UIButton
            {
                Text = "打印报告",
                Size = new Size(100, 40),
                FillColor = Color.FromArgb(255, 184, 0),
                ForeColor = Color.White,
                Cursor = Cursors.Hand,
                Anchor = AnchorStyles.Bottom | AnchorStyles.Right
            };
            btnPrint.Click += BtnPrint_Click;

            var btnClose = new UIButton
            {
                Text = "关闭",
                Size = new Size(80, 40),
                FillColor = Color.FromArgb(255, 87, 87),
                ForeColor = Color.White,
                Cursor = Cursors.Hand,
                Anchor = AnchorStyles.Bottom | AnchorStyles.Right
            };
            btnClose.Click += (s, e) => this.Close();

            buttonPanel.Controls.Add(btnExport);
            buttonPanel.Controls.Add(btnPrintPreview);
            buttonPanel.Controls.Add(btnPrint);
            buttonPanel.Controls.Add(btnClose);

            // 处理窗体大小变化时按钮位置调整
            buttonPanel.SizeChanged += (s, e) =>
            {
                btnExport.Location = new Point(buttonPanel.Width - 420, 10);
                btnPrintPreview.Location = new Point(buttonPanel.Width - 310, 10);
                btnPrint.Location = new Point(buttonPanel.Width - 200, 10);
                btnClose.Location = new Point(buttonPanel.Width - 90, 10);
            };

            return buttonPanel;
        }

        private void LoadData()
        {
            try
            {
                string resultText = BuildDetailedResultText();
                txtResultDisplay.Text = resultText;
            }
            catch (Exception ex)
            {
                txtResultDisplay.Text = $"加载数据失败: {ex.Message}";
                UIMessageBox.ShowError($"加载数据失败：{ex.Message}");
            }
        }

        /// <summary>
        /// 构建详细结果文本 - 统一显示所有内容
        /// </summary>
        private string BuildDetailedResultText()
        {
            var sb = new StringBuilder();

            // 标题
            sb.AppendLine("=== 测量结果详细报告 ===");
            sb.AppendLine($"生成时间: {DateTime.Now:yyyy-MM-dd HH:mm:ss}");
            sb.AppendLine();

            // 基本信息
            BuildBasicInfo(sb);
            sb.AppendLine();

            //// 计算参数配置
            //BuildCalculationParameters(sb);
            //sb.AppendLine();

            //// 计算上下文信息
            //BuildCalculationContext(sb);
            //sb.AppendLine();

            // 各通道均值结果
            BuildAverageResults(sb);
            sb.AppendLine();

            // 各轮详细结果
            BuildRoundResults(sb);
            sb.AppendLine();

            //// 数据质量评估
            //BuildQualityAssessment(sb);
            //sb.AppendLine();

            //// 统计分析
            //BuildStatisticalAnalysis(sb);

            return sb.ToString();
        }

        private void BuildBasicInfo(StringBuilder sb)
        {
            sb.AppendLine("【测量基本信息】");
            sb.AppendLine($"测量类型: {GetMeasurementTypeDisplayName(measurementData.MeasurementType)}");
            sb.AppendLine($"总轮数: {measurementData.TotalRounds}");
            sb.AppendLine($"每轮时间: {measurementData.MeasurementTimeMinutes} 分钟");
            sb.AppendLine($"开始时间: {measurementData.StartTime:yyyy-MM-dd HH:mm:ss}");
            sb.AppendLine($"结束时间: {measurementData.EndTime:yyyy-MM-dd HH:mm:ss}");
            sb.AppendLine($"总耗时: {(measurementData.EndTime - measurementData.StartTime).TotalMinutes:F1} 分钟");
            //sb.AppendLine($"测量ID: {measurementData.MeasurementId}");
            //sb.AppendLine($"参与通道: {measurementData.ChannelResults.Count} 个 ({string.Join(", ", measurementData.ChannelResults.Keys.OrderBy(k => k).Select(k => $"通道{k + 1}"))})");
        }

        private void BuildCalculationParameters(StringBuilder sb)
        {
            sb.AppendLine("【计算参数配置】");
            try
            {
                if (measurementData.Parameters == null)
                {
                    sb.AppendLine("无特殊参数配置");
                    return;
                }

                var parametersJson = JsonConvert.SerializeObject(measurementData.Parameters, Formatting.Indented);

                switch (measurementData.MeasurementType)
                {
                    case "WorkingSourceEfficiency":
                        FormatWorkingSourceParameters(sb, parametersJson);
                        break;
                    case "StandardSourceEfficiency":
                        FormatStandardSourceParameters(sb, parametersJson);
                        break;
                    case "WaterSample":
                        FormatWaterSampleParameters(sb, parametersJson);
                        break;
                    case "BioSample":
                        FormatBioSampleParameters(sb, parametersJson);
                        break;
                    case "GasSample":
                        FormatGasSampleParameters(sb, parametersJson);
                        break;
                    case "EnvSample":
                        FormatEnvSampleParameters(sb, parametersJson);
                        break;
                    default:
                        sb.AppendLine($"参数类型: {measurementData.MeasurementType}");
                        sb.AppendLine(parametersJson);
                        break;
                }
            }
            catch (Exception ex)
            {
                sb.AppendLine($"参数信息获取失败: {ex.Message}");
            }
        }

        private void BuildCalculationContext(StringBuilder sb)
        {
            sb.AppendLine("【计算配置信息】");
            try
            {
                if (measurementData.CalculationContext != null)
                {
                    var context = measurementData.CalculationContext;
                    sb.AppendLine($"计算器类型: {context.CalculatorType}");
                    sb.AppendLine($"选中通道: {string.Join(", ", context.SelectedChannels.Select(c => $"通道{c + 1}"))}");
                    sb.AppendLine($"上下文创建: {context.ContextCreatedTime:yyyy-MM-dd HH:mm:ss}");
                    if (context.Parameters != null)
                    {
                        sb.AppendLine($"计算参数: 已配置 ({measurementData.MeasurementType} 专用参数)");
                    }
                }
                else
                {
                    sb.AppendLine("无计算上下文信息");
                }
            }
            catch (Exception ex)
            {
                sb.AppendLine($"计算上下文信息获取失败: {ex.Message}");
            }
        }

        private void BuildAverageResults(StringBuilder sb)
        {
            sb.AppendLine("【各通道均值结果】");
            sb.AppendLine($"{"通道",-6} {"α均值",-15} {"β均值",-15}");
            sb.AppendLine(new string('-', 70));

            foreach (var channelKvp in measurementData.ChannelResults.OrderBy(kvp => kvp.Key))
            {
                int channelIndex = channelKvp.Key;
                var avgResult = channelKvp.Value.AverageResult;
                var statistics = channelKvp.Value.Statistics;

                if (avgResult != null && statistics != null)
                {
                    sb.AppendLine($"CH{channelIndex + 1,-5} {avgResult.AlphaResult,-15:F6} {avgResult.BetaResult,-15:F6} " +
                                 $"{statistics.AlphaStandardDeviation,-15:F6} {statistics.BetaStandardDeviation,-15:F6}");
                }
                else if (avgResult != null)
                {
                    sb.AppendLine($"CH{channelIndex + 1,-5} {avgResult.AlphaResult,-15:F6} {avgResult.BetaResult,-15:F6} " +
                                 $"{"---",-15} {"---",-15}");
                }
                else
                {
                    sb.AppendLine($"CH{channelIndex + 1,-5} {"---",-15} {"---",-15} {"---",-15} {"---",-15}");
                }
            }
        }

        private void BuildRoundResults(StringBuilder sb)
        {
            sb.AppendLine("【各轮详细结果】");

            var allRounds = GetAllRoundsSorted();

            foreach (var roundData in allRounds)
            {
                sb.AppendLine($"第 {roundData.RoundNumber} 轮测量结果:");

                // 时间信息
                if (roundData.Results.Count > 0)
                {
                    var firstResult = roundData.Results[0];
                    sb.Append($"  时间: {firstResult.Timestamp:yyyy-MM-dd HH:mm:ss}");
                    if (firstResult.MeasurementDurationSeconds > 0)
                    {
                        sb.Append($"  测量时长: {firstResult.MeasurementDurationSeconds}秒");
                    }
                    sb.AppendLine();
                }

                // 各通道结果
                foreach (var result in roundData.Results.OrderBy(r => r.ChannelIndex))
                {
                    sb.AppendLine($"  通道 {result.ChannelIndex + 1}:");
                    sb.AppendLine($"    α = {result.AlphaResult:F6} (计数率: {result.AlphaCountRate:F3}/s" +
                                 (result.AlphaTotalCounts > 0 ? $", 总点数: {result.AlphaTotalCounts}" : "") + ")");
                    sb.AppendLine($"    β = {result.BetaResult:F6} (计数率: {result.BetaCountRate:F3}/s" +
                                 (result.BetaTotalCounts > 0 ? $", 总点数: {result.BetaTotalCounts}" : "") + ")");
                }
                sb.AppendLine();
            }
        }

        private void BuildQualityAssessment(StringBuilder sb)
        {
            sb.AppendLine("【数据质量评估】");

            var allAlphaErrors = measurementData.ChannelResults.Values
                .Where(c => c.Statistics != null)
                .Select(c => c.Statistics.AlphaRelativeError);
            var allBetaErrors = measurementData.ChannelResults.Values
                .Where(c => c.Statistics != null)
                .Select(c => c.Statistics.BetaRelativeError);

            if (allAlphaErrors.Any() && allBetaErrors.Any())
            {
                sb.AppendLine($"α平均相对误差: {allAlphaErrors.Average():F2}%");
                sb.AppendLine($"β平均相对误差: {allBetaErrors.Average():F2}%");
                sb.AppendLine($"α最大相对误差: {allAlphaErrors.Max():F2}%");
                sb.AppendLine($"β最大相对误差: {allBetaErrors.Max():F2}%");
                sb.AppendLine($"α最小相对误差: {allAlphaErrors.Min():F2}%");
                sb.AppendLine($"β最小相对误差: {allBetaErrors.Min():F2}%");
            }
            else
            {
                sb.AppendLine("统计信息不足，无法评估数据质量");
            }
        }

        private void BuildStatisticalAnalysis(StringBuilder sb)
        {
            sb.AppendLine("【统计分析】");

            int totalMeasurements = measurementData.ChannelResults.Values.Sum(c => c.RoundResults.Count);
            double totalTime = (measurementData.EndTime - measurementData.StartTime).TotalMinutes;
            double avgTimePerRound = totalTime / measurementData.TotalRounds;

            sb.AppendLine($"├─ 总测量次数: {totalMeasurements}");
            sb.AppendLine($"├─ 总测量轮数: {measurementData.TotalRounds}");
            sb.AppendLine($"├─ 总测量时长: {totalTime:F1} 分钟 ({totalTime / 60:F1} 小时)");
            sb.AppendLine($"├─ 平均每轮耗时: {avgTimePerRound:F1} 分钟");
            sb.AppendLine($"├─ 参与通道数: {measurementData.ChannelResults.Count}");
            sb.AppendLine($"└─ 数据完整性: {(totalMeasurements == measurementData.TotalRounds * measurementData.ChannelResults.Count ? "完整" : "部分缺失")}");

            sb.AppendLine();
            sb.AppendLine("【数据保存信息】");
            sb.AppendLine($"JSON文件保存: 全局文件 + 按通道分组文件");
            sb.AppendLine($"数据库保存: 计算结果已保存");
            sb.AppendLine($"文件标识: {measurementData.MeasurementId}");
            sb.AppendLine($"报告生成时间: {DateTime.Now:yyyy-MM-dd HH:mm:ss}");
        }

        // 参数格式化方法（增强错误处理）
        private void FormatWorkingSourceParameters(StringBuilder sb, string parametersJson)
        {
            try
            {
                var parameters = JsonConvert.DeserializeObject<dynamic>(parametersJson);
                sb.AppendLine("工作源效率测量参数:");

                if (parameters.GeometryFactor != null)
                    sb.AppendLine($"几何因子: {parameters.GeometryFactor}");

                if (parameters.AlphaEmissionRates != null)
                {
                    sb.Append("α发射率配置: ");
                    try
                    {
                        var alphaRates = ParseEmissionRates(parameters.AlphaEmissionRates);
                        for (int i = 0; i < alphaRates.Length && i < measurementData.ChannelResults.Count; i++)
                        {
                            if (measurementData.ChannelResults.ContainsKey(i))
                            {
                                sb.Append($"通道{i + 1}={alphaRates[i]:F1} ");
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        sb.Append($"解析失败({ex.Message})");
                    }
                    sb.AppendLine();
                }

                if (parameters.BetaEmissionRates != null)
                {
                    sb.Append("β发射率配置: ");
                    try
                    {
                        var betaRates = ParseEmissionRates(parameters.BetaEmissionRates);
                        for (int i = 0; i < betaRates.Length && i < measurementData.ChannelResults.Count; i++)
                        {
                            if (measurementData.ChannelResults.ContainsKey(i))
                            {
                                sb.Append($"通道{i + 1}={betaRates[i]:F1} ");
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        sb.Append($"解析失败({ex.Message})");
                    }
                    sb.AppendLine();
                }
            }
            catch (Exception ex)
            {
                sb.AppendLine($"工作源效率参数解析失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 解析发射率数据，支持多种JSON格式
        /// </summary>
        private double[] ParseEmissionRates(dynamic rates)
        {
            try
            {
                // 处理JArray类型
                if (rates is Newtonsoft.Json.Linq.JArray jArray)
                {
                    return jArray.ToObject<double[]>();
                }

                // 处理JObject类型（可能是字典格式）
                if (rates is Newtonsoft.Json.Linq.JObject jObject)
                {
                    var dict = jObject.ToObject<Dictionary<string, double>>();
                    return dict?.Values.ToArray() ?? new double[0];
                }

                // 处理JToken类型
                if (rates is Newtonsoft.Json.Linq.JToken jToken)
                {
                    if (jToken.Type == Newtonsoft.Json.Linq.JTokenType.Array)
                    {
                        return jToken.ToObject<double[]>();
                    }
                    else if (jToken.Type == Newtonsoft.Json.Linq.JTokenType.Object)
                    {
                        var dict = jToken.ToObject<Dictionary<string, double>>();
                        return dict?.Values.ToArray() ?? new double[0];
                    }
                }

                // 尝试直接转换
                return new double[] { Convert.ToDouble(rates) };
            }
            catch
            {
                return new double[0];
            }
        }

        /// <summary>
        /// 解析质量数据，支持多种JSON格式
        /// </summary>
        private double[] ParseMassData(dynamic masses)
        {
            try
            {
                // 处理JArray类型
                if (masses is Newtonsoft.Json.Linq.JArray jArray)
                {
                    return jArray.ToObject<double[]>();
                }

                // 处理JObject类型（可能是字典格式）
                if (masses is Newtonsoft.Json.Linq.JObject jObject)
                {
                    var dict = jObject.ToObject<Dictionary<string, double>>();
                    return dict?.Values.ToArray() ?? new double[0];
                }

                // 处理JToken类型
                if (masses is Newtonsoft.Json.Linq.JToken jToken)
                {
                    if (jToken.Type == Newtonsoft.Json.Linq.JTokenType.Array)
                    {
                        return jToken.ToObject<double[]>();
                    }
                    else if (jToken.Type == Newtonsoft.Json.Linq.JTokenType.Object)
                    {
                        var dict = jToken.ToObject<Dictionary<string, double>>();
                        return dict?.Values.ToArray() ?? new double[0];
                    }
                }

                // 尝试直接转换
                return new double[] { Convert.ToDouble(masses) };
            }
            catch
            {
                return new double[0];
            }
        }

        private void FormatStandardSourceParameters(StringBuilder sb, string parametersJson)
        {
            try
            {
                var parameters = JsonConvert.DeserializeObject<dynamic>(parametersJson);
                sb.AppendLine("标准源效率测量参数:");

                if (parameters.AlphaSpecificActivity != null)
                {
                    sb.Append("α比活度: ");
                    try
                    {
                        var alphaActivities = ParseEmissionRates(parameters.AlphaSpecificActivity);
                        for (int i = 0; i < alphaActivities.Length && i < measurementData.ChannelResults.Count; i++)
                        {
                            if (measurementData.ChannelResults.ContainsKey(i))
                            {
                                sb.Append($"通道{i + 1}={alphaActivities[i]:F1} ");
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        sb.Append($"解析失败({ex.Message})");
                    }
                    sb.AppendLine();
                }

                if (parameters.BetaSpecificActivity != null)
                {
                    sb.Append("β比活度: ");
                    try
                    {
                        var betaActivities = ParseEmissionRates(parameters.BetaSpecificActivity);
                        for (int i = 0; i < betaActivities.Length && i < measurementData.ChannelResults.Count; i++)
                        {
                            if (measurementData.ChannelResults.ContainsKey(i))
                            {
                                sb.Append($"通道{i + 1}={betaActivities[i]:F1} ");
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        sb.Append($"解析失败({ex.Message})");
                    }
                    sb.AppendLine();
                }

                if (parameters.SourceMass != null)
                {
                    sb.Append("源质量: ");
                    try
                    {
                        var sourceMasses = ParseMassData(parameters.SourceMass);
                        for (int i = 0; i < sourceMasses.Length && i < measurementData.ChannelResults.Count; i++)
                        {
                            if (measurementData.ChannelResults.ContainsKey(i))
                            {
                                sb.Append($"通道{i + 1}={sourceMasses[i]:F2}g ");
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        sb.Append($"解析失败({ex.Message})");
                    }
                    sb.AppendLine();
                }
            }
            catch (Exception ex)
            {
                sb.AppendLine($"标准源效率参数解析失败: {ex.Message}");
            }
        }

        private void FormatWaterSampleParameters(StringBuilder sb, string parametersJson)
        {
            try
            {
                var parameters = JsonConvert.DeserializeObject<dynamic>(parametersJson);
                sb.AppendLine("水样品测量参数:");

                if (parameters.WaterVolume != null)
                    sb.AppendLine($"水样体积: {parameters.WaterVolume} L");
                if (parameters.TotalResidueAmount != null)
                    sb.AppendLine($"总残渣量: {parameters.TotalResidueAmount} g");
                if (parameters.TestedSampleMass != null)
                    sb.AppendLine($"测试样品质量: {parameters.TestedSampleMass} g");
                if (parameters.UseStandardEfficiency != null)
                    sb.AppendLine($"使用标准效率: {(bool)parameters.UseStandardEfficiency}");
            }
            catch (Exception ex)
            {
                sb.AppendLine($"水样品参数解析失败: {ex.Message}");
                sb.AppendLine($"原始JSON: {parametersJson}");
            }
        }

        private void FormatBioSampleParameters(StringBuilder sb, string parametersJson)
        {
            try
            {
                var parameters = JsonConvert.DeserializeObject<dynamic>(parametersJson);
                sb.AppendLine("生物样品测量参数:");

                if (parameters.FreshSampleWeight != null)
                    sb.AppendLine($"鲜样重量: {parameters.FreshSampleWeight} g");
                if (parameters.TestedSampleMass != null)
                    sb.AppendLine($"测试样品质量: {parameters.TestedSampleMass} g");
                if (parameters.TotalAshWeight != null)
                    sb.AppendLine($"总灰重: {parameters.TotalAshWeight} g");
                if (parameters.RecoveryRate != null)
                    sb.AppendLine($"回收率: {parameters.RecoveryRate:F2}%");
                if (parameters.UseStandardEfficiency != null)
                    sb.AppendLine($"使用标准效率: {(bool)parameters.UseStandardEfficiency}");
            }
            catch (Exception ex)
            {
                sb.AppendLine($"生物样品参数解析失败: {ex.Message}");
                sb.AppendLine($"原始JSON: {parametersJson}");
            }
        }

        private void FormatGasSampleParameters(StringBuilder sb, string parametersJson)
        {
            try
            {
                var parameters = JsonConvert.DeserializeObject<dynamic>(parametersJson);
                sb.AppendLine("气体样品测量参数:");

                if (parameters.SamplingVolume != null)
                    sb.AppendLine($"采样体积: {parameters.SamplingVolume} m³");
                if (parameters.FilterEfficiency != null)
                    sb.AppendLine($"过滤效率: {parameters.FilterEfficiency:F2}%");
                if (parameters.AbsorptionFactor != null)
                    sb.AppendLine($"吸收因子: {parameters.AbsorptionFactor:F3}");
                if (parameters.UseStandardEfficiency != null)
                    sb.AppendLine($"使用标准效率: {(bool)parameters.UseStandardEfficiency}");
            }
            catch (Exception ex)
            {
                sb.AppendLine($"气体样品参数解析失败: {ex.Message}");
                sb.AppendLine($"原始JSON: {parametersJson}");
            }
        }

        private void FormatEnvSampleParameters(StringBuilder sb, string parametersJson)
        {
            try
            {
                var parameters = JsonConvert.DeserializeObject<dynamic>(parametersJson);
                sb.AppendLine("环境样品测量参数:");

                if (parameters.TestedSampleMass != null)
                    sb.AppendLine($"测试样品质量: {parameters.TestedSampleMass} g");
                if (parameters.CorrectionFactor != null)
                    sb.AppendLine($"修正因子: {parameters.CorrectionFactor:F3}");
                if (parameters.UseStandardEfficiency != null)
                    sb.AppendLine($"使用标准效率: {(bool)parameters.UseStandardEfficiency}");
            }
            catch (Exception ex)
            {
                sb.AppendLine($"环境样品参数解析失败: {ex.Message}");
                sb.AppendLine($"原始JSON: {parametersJson}");
            }
        }

        private List<RoundData> GetAllRoundsSorted()
        {
            var roundsDict = new Dictionary<int, RoundData>();

            foreach (var channelKvp in measurementData.ChannelResults)
            {
                int channelIndex = channelKvp.Key;
                var channelData = channelKvp.Value;

                foreach (var roundResult in channelData.RoundResults)
                {
                    if (!roundsDict.ContainsKey(roundResult.RoundNumber))
                    {
                        roundsDict[roundResult.RoundNumber] = new RoundData
                        {
                            RoundNumber = roundResult.RoundNumber
                        };
                    }

                    roundsDict[roundResult.RoundNumber].Results.Add(new ChannelRoundResult
                    {
                        ChannelIndex = channelIndex,
                        AlphaResult = roundResult.AlphaResult,
                        BetaResult = roundResult.BetaResult,
                        AlphaCountRate = roundResult.AlphaCountRate,
                        BetaCountRate = roundResult.BetaCountRate,
                        Timestamp = roundResult.Timestamp,
                        AlphaTotalCounts = roundResult.AlphaTotalCounts,
                        BetaTotalCounts = roundResult.BetaTotalCounts,
                        MeasurementDurationSeconds = roundResult.MeasurementDurationSeconds
                    });
                }
            }

            return roundsDict.Values.OrderBy(r => r.RoundNumber).ToList();
        }

        private string GetMeasurementTypeDisplayName(string englishType)
        {
            switch (englishType)
            {
                case "WorkingSourceEfficiency":
                    return "工作源效率测量";
                case "StandardSourceEfficiency":
                    return "标准源效率测量";
                case "WaterSample":
                    return "水样品测量";
                case "BioSample":
                    return "生物样品测量";
                case "GasSample":
                    return "气体样品测量";
                case "EnvSample":
                    return "环境样品测量";
                case "Background":
                    return "本底测量";
                default:
                    return englishType;
            }
        }

        #region 事件处理方法

        private void BtnExport_Click(object sender, EventArgs e)
        {
            try
            {
                SaveFileDialog saveDialog = new SaveFileDialog();
                saveDialog.Filter = "文本文件 (*.txt)|*.txt|所有文件 (*.*)|*.*";
                saveDialog.FileName = $"测量报告_{measurementData.MeasurementType}_{DateTime.Now:yyyyMMdd_HHmmss}.txt";

                if (saveDialog.ShowDialog() == DialogResult.OK)
                {
                    System.IO.File.WriteAllText(saveDialog.FileName, txtResultDisplay.Text, System.Text.Encoding.UTF8);
                    UIMessageBox.ShowSuccess($"报告已导出到：\n{saveDialog.FileName}");
                }
            }
            catch (Exception ex)
            {
                UIMessageBox.ShowError($"导出失败：{ex.Message}");
            }
        }

        private void BtnPrint_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(txtResultDisplay.Text))
                {
                    UIMessageBox.ShowWarning("没有可打印的内容！");
                    return;
                }

                printLines = txtResultDisplay.Text.Split('\n');
                printLineIndex = 0;

                PrintDialog printDialog = new PrintDialog();
                printDialog.Document = printDocument;

                if (printDialog.ShowDialog() == DialogResult.OK)
                {
                    printDocument.Print();
                    UIMessageBox.ShowSuccess("打印任务已发送到打印机！");
                }
            }
            catch (Exception ex)
            {
                UIMessageBox.ShowError($"打印失败：{ex.Message}");
            }
        }

        private void BtnPrintPreview_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(txtResultDisplay.Text))
                {
                    UIMessageBox.ShowWarning("没有可预览的内容！");
                    return;
                }

                printLines = txtResultDisplay.Text.Split('\n');
                printLineIndex = 0;
                printPreviewDialog.ShowDialog();
            }
            catch (Exception ex)
            {
                UIMessageBox.ShowError($"打印预览失败：{ex.Message}");
            }
        }

        #endregion

        #region 打印相关方法

        /// <summary>
        /// 打印文档的PrintPage事件处理 - 与AllChannelsMeasurementResultsForm保持一致
        /// </summary>
        private void PrintDocument_PrintPage(object sender, PrintPageEventArgs e)
        {
            try
            {
                Font printFont = new Font("宋体", 9F);
                Font titleFont = new Font("宋体", 12F, FontStyle.Bold);
                float leftMargin = e.MarginBounds.Left;
                float topMargin = e.MarginBounds.Top;
                float yPos = topMargin;
                float lineHeight = printFont.GetHeight(e.Graphics);

                // 打印标题
                //string title = $"多轮测量结果报告 - 第{((printLineIndex == 0) ? 1 : (printLineIndex / 50 + 1))}页";
                //e.Graphics.DrawString(title, titleFont, Brushes.Black, leftMargin, yPos);
                yPos += titleFont.GetHeight(e.Graphics) * 2;

                // 计算每页可打印的行数
                int linesPerPage = (int)((e.MarginBounds.Height - titleFont.GetHeight(e.Graphics) * 2) / lineHeight);
                int linesOnThisPage = 0;

                // 打印文本内容
                while (printLineIndex < printLines.Length && linesOnThisPage < linesPerPage)
                {
                    string line = printLines[printLineIndex];

                    // 检查是否需要换行（行太长）
                    SizeF textSize = e.Graphics.MeasureString(line, printFont);
                    if (textSize.Width > e.MarginBounds.Width)
                    {
                        // 分割长行
                        int charsPerLine = (int)(line.Length * e.MarginBounds.Width / textSize.Width) - 5;
                        if (charsPerLine > 0)
                        {
                            string subLine = line.Substring(0, Math.Min(charsPerLine, line.Length));
                            e.Graphics.DrawString(subLine, printFont, Brushes.Black, leftMargin, yPos);

                            if (line.Length > charsPerLine)
                            {
                                printLines[printLineIndex] = line.Substring(charsPerLine);
                            }
                            else
                            {
                                printLineIndex++;
                            }
                        }
                        else
                        {
                            e.Graphics.DrawString(line, printFont, Brushes.Black, leftMargin, yPos);
                            printLineIndex++;
                        }
                    }
                    else
                    {
                        e.Graphics.DrawString(line, printFont, Brushes.Black, leftMargin, yPos);
                        printLineIndex++;
                    }

                    yPos += lineHeight;
                    linesOnThisPage++;
                }

                // 判断是否还有更多页需要打印
                e.HasMorePages = (printLineIndex < printLines.Length);
            }
            catch (Exception ex)
            {
                UIMessageBox.ShowError($"打印过程中发生错误：{ex.Message}");
                e.HasMorePages = false;
            }
        }

        /// <summary>
        /// 窗体关闭时清理资源
        /// </summary>
        protected override void OnFormClosed(FormClosedEventArgs e)
        {
            printDocument?.Dispose();
            printPreviewDialog?.Dispose();
            base.OnFormClosed(e);
        }

        #endregion
    }
}